<?php

class ForgotpassController extends Controller{
    
    function actionIndex(){
        $this->actionDo();
    }
    
    function actionDo(){
        
        $this->layout = '//layouts/column1';
        
        if(Yii::app()->user->isAuth()){
            $this->redirect($this->createUrl('/user'));
        }
        
        $_FORM = new FormForgotpass;
        
        if($_POST['FormForgotpass']){
            $_FORM->attributes = $_POST['FormForgotpass'];
            if($_FORM->validate()){
                $_FORM->sendRequest();
                Yii::app()->user->successMesasge($this, 'Запрос на смену пароля выслан Вам на e-mail.');
                $this->redirect($this->createUrl('login/do'));
            }
        }
        
        $checkword = trim(substr(strip_tags($_GET['checkword']), 0, 32));
        $email = trim(substr(strip_tags($_GET['email']), 0, 32));
        
        if(!empty($checkword) and !empty($email)){
            
            $USER = Users::model()->findByAttributes(array(
                'email' => $email,
            ));
            
            if(count($USER) <= 0){
                Yii::app()->user->errorMessage($this, 'Пользователь с таким e-mail не найден.');
            }else{
                
                if($_FORM->makeNewPass($USER, $checkword)){
                    Yii::app()->user->successMesasge($this, 'Пароль успешно изменён. Новый пароль выслан Вам на e-mail.');
                }else{
                    Yii::app()->user->errorMessage($this, 'Ошибка изменения пароля.');
                }
                
                $this->redirect($this->createUrl('login/do'));
                
            }
            
        }
        
        $this->render('form-forgotpass', array(
            '_FORM' => $_FORM
        ));
    }
    
}
